<template>
  <section>
    <div class="left">
      <VideoList :list="list" :cfg="VideoListCfg" v-show="mode2==='video'">
        <div class="page noBlueBg">
          <el-pagination
            @current-change="changePage"
            :current-page="page"
            :page-size="limit"
            layout="total,prev, pager, next, jumper"
            :total="totals">
          </el-pagination>
        </div>

        <div class="groupBy ml20">
          <el-select v-model="groupType" placeholder="请选择分组类型" clearable size="mini" style="width: 120px;display: inline-block">
            <el-option
              v-for="(value,key) in groups"
              :key="key"
              :label="value"
              :value="key.toString()">
            </el-option>
          </el-select>
          <el-input v-model="groupValue" placeholder="请输入分组名称" clearable style="width: 120px;" size="mini" class="mh5"
                    clearable></el-input>
          <el-button size="mini" type="primary" @click="loadEventList(1)">查询分组</el-button>
        </div>
      </VideoList>
      <ImageList :list="list" :cfg="VideoListCfg" v-show="mode2==='image'">
        <div class="page noBlueBg">
          <el-pagination
            @current-change="changePage"
            :current-page="page"
            :page-size="limit"
            layout="total,prev, pager, next, jumper"
            :total="totals">
          </el-pagination>
        </div>
        <div class="groupBy ml20">
          <el-select v-model="groupType" placeholder="请选择分组类型" size="mini" clearable style="width: 120px;display: inline-block">
            <el-option
              v-for="(value,key) in groups"
              :key="key"
              :label="value"
              :value="key.toString()">
            </el-option>
          </el-select>
          <el-input v-model="groupValue" placeholder="请输入分组名称" clearable style="width: 120px;" size="mini" class="mh5"
                    clearable></el-input>
          <el-button size="mini" type="primary" @click="loadEventList(2)">查询分组</el-button>
        </div>
      </ImageList>
    </div>
    <div class="right">
      <h4>当前选择：</h4>
      <div class="checkedList">
        <div class="content" :style="{maxHeight:listHeight+'px'}">
          <div v-show="checkedItems.length===0" style="text-align: center; margin-top: 100px; opacity: .5;">
            请勾选要处置的事件！
          </div>
          <div class="list-item" v-for="item in checkedItems">
            <ul>
              <li><label>类型:</label>{{dict['event'][item.eventTypeTwoCode]}}</li>
              <li><label>状态:</label>{{item.stateName}}</li>
              <li v-if="item.eventTypeTwoCode==='002-007-002'"><label>能见度:</label>{{item.distance}}米</li>
              <li><label>路段:</label>{{item.road}}</li>
              <li><label>位置:</label>{{item.position}}</li>
              <li><label>时间:</label>{{item.detectedTime}}</li>
            </ul>
            <div class="img">
              <img :src="item.source===2?item.imgPath:webCfg.api.url+':'+webCfg.api.fileSvrPort+'/'+item.imgPath" @click="viewBigImg($event)">
            </div>
          </div>
        </div>
      </div>
      <div class="action" v-show="checkedItems.length>0" :style="{height:bottomHeight+'px'}" v-if="identityId==='2' || identityId==='5'">
        <div v-if="mode==='uncheck'">
          <el-button type="primary" size="mini" @click="handle(1)">稽核</el-button>
        </div>
        <div v-if="mode==='checked'">
          <el-button type="primary" size="mini" @click="handle(2,1)">发布</el-button>
          <el-button type="warning" size="mini" @click="handle(2,0)">忽略</el-button>
        </div>
      </div>
    </div>
    <div class="tools">
      <el-button type="primary" size="small" @click="changeMode('uncheck')" :class="{active:mode==='uncheck'}">
        未稽核
      </el-button>
      <br>
      <el-button type="primary" size="small" @click="changeMode('checked')" :class="{active:mode==='checked'}">
        已稽核
      </el-button>
    </div>
    <Dialog :cfg="dialogCfg" ref="dialog">
      <div v-if="mode==='uncheck'">
        <el-form ref="fun1Form" label-width="70px">
          <el-form-item label="事件：">
            <el-select v-model="evtType" placeholder="请选择事件类型" size="mini" clearable>
              <el-option
                v-for="(label,value) in evtTypes"
                :key="value"
                :label="label.indexOf('-')>-1?label.split('-')[1]:label"
                :value="value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="note" placeholder="请输入备注内容" size="mini" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
    </Dialog>

    <Dialog :cfg="dialogCfg" ref="dialog2">
      <div v-if="mode==='checked'">
        <el-form ref="fun1Form" label-width="120px"
                 label-position="top" class="eventInfoBox" :model="fbFormData" :rules="fbRules">
          <el-form-item label="事件处理：" class="eventInfoBox2" prop="handle">
            <el-select v-model="fbFormData.handle" multiple placeholder="请选择单位" size="mini" style="width: 100%">
              <el-option
                v-for="item in orgData.center"
                :key="item.id"
                :label="item.name"
                :value="item.id.toString()">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="处理时限：" prop="expectTimeTwoNum">
            <el-select
              size="mini"
              v-model="fbFormData.expectTimeTwoNum"

              filterable
              default-first-option
              placeholder="请选择处理时限">
              <el-option
                v-for="item in timeSpaces"
                :key="item"
                :label="item+'分钟'"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注：" prop="remark2">
            <el-input v-model="fbFormData.remark2"
                      placeholder="请输入备注内容" size="mini"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </Dialog>
  </section>
</template>

<script>
  import ImageList from "comp/common/ImageList";
  import VideoList from 'comp/common/VideoList2';
  import Dialog from 'comp/common/Dialog.vue';

  export default {
    name: "Disposal",
    components: {
      ImageList,
      VideoList,
      Dialog
    },
    data() {
      return {
        orgData: {},
        groups: this.$kkui.cache.get('dict')['cameraGroup'],
        webCfg: WebCfg,
        mode: 'uncheck',
        mode2: 'video',
        icons: WebCfg.icons,

        limit: 16,
        page: 1,
        pages: 1,
        totals: 0,
        groupType: '',
        groupValue: '',
        list: [],
        dict: this.$kkui.cache.get('dict'),
        dialogCfg: {
          width: 600,
          height: 400,
          title: '',
          closeShow: !!1,
          footerShow: !!1,
          submit: () => {
          }
        },
        note: '',
        evtType: '',
        evtTypes: '',

        units: [],
        curUnit: '',
        departments: [],
        curDepartment: '',
        receive: '',
        receives: [],
        sendBaseFlag: true,


        listHeight: 500,
        bottomHeight: 50,
        VideoListCfg: {},
        checkedItems: [],

        fbFormData: {
          handle: '',
          expectTimeTwoNum: '5',
          remark2: ''
        },
        fbRules: {
          handle: [
            {required: true, type: 'array', message: '事件处理单位不能为空！', change: 'change'}
          ],
          expectTimeTwoNum: [
            {required: true, message: '处理时限不能为空！', change: 'change'}
          ]
        },
        timeSpaces:WebCfg['timeSpaces'],
        departments2: [],
        identityId: this.$kkui.cache.get('user')['identityId'],
        kuaisulu: ''
      }
    },
    mounted() {
      this.initSize();
      const dist = this.$kkui.cache.get('dict');
      this.getDepartments2();
      this.evtTypes = dist['event'];
      this.$kkui.loading_deepBlue.hide();
      this.loadEventList(1);

      this.evtTypes = {};
      Object.keys(this.dict['event']).map(key => {
        return {
          key,
          value: this.dict['event'][key]
        }
      }).sort(function (a, b) {
        return b.value.localeCompare(a.value)
      }).forEach(item => {
        this.evtTypes[item.key] = item.value;
      });
      this.getOrgData();
    },
    methods: {
      getDepartments2() {
        this.$server('org.list').then(data => {
          this.departments2 = [];
          data.forEach(item => {
            if (item.name !== '各分中心') {
              item.children.forEach(itm => {
                this.departments2.push(itm);
              })
            }
          })
        })
      },
      getOrgData() {
        this.$server('org.list').then(data => {
          let orgData = {center: [], base: []};
          data.forEach(item => {
            if (item.name === '各分中心' || item.name === '联动单位') {
              orgData.center = orgData.center.concat(item.children);
              if (item.name === '各分中心') {
                item.children.forEach(item => {
                  if (item.name === '快速路') {
                    this.kuaisulu = [item.id].toString();
                  }
                })
              }
            } else {
              orgData.base = orgData.base.concat(item.children)
            }
          });
          this.orgData = orgData;
        })
      },
      //加载事件列表
      loadEventList(state) {
        //超级管理员id=1，后续对超管用户控制不可删除，以防止用户误删
       if(!this.$kkui.cache.get('user')['roleId']==1){
        this.group = this.$kkui.cache.get('user')['deptId'];
       }
        this.$server('monitor.list', {
          limit: this.limit,
          page: this.page,
          state: state,
          groupType: this.groupType,
          groupValue: this.groupValue
        }).then(data => {
          this.list = data['records'].map(item => {
            return {
              ...item,
              stateName: this.dict['status'][item.state],
              code: item.eventTypeTwoCode,
              type: 'event',
              road: item['bscCamera'] && item['bscCamera'].road,
              position: item['bscCamera'] && item['bscCamera'].name,
              imagePath: item.imgPath,
              videoPath: item.videoPath,
              source:item.source
            }
          });
          this.totals = data['total'];
          this.$kkui.loading_deepBlue.hide();
        })
      },

      //切换分页
      changePage(page) {
        this.page = page;
        this.loadEventList(this.mode === 'uncheck' ? 1 : 2);
      },

      selectItem(list) {
        this.checkedItems = [];
        let types = '';
        list.forEach(id => {
          const filterArr = this.list.filter(itm => itm.id === id);
          if (filterArr.length === 1) {
            this.checkedItems.push(filterArr[0]);
            if (!types) types = filterArr[0]['code'];
          }
        });

        this.evtType = types;


      },
      changeMode(mode) {
        this.mode = mode;
        this.loadEventList(mode === 'uncheck' ? 1 : 2);
        this.checkedItems = [];
      },

      changeMode2(mode2) {
        this.mode2 = mode2;
        this.loadEventList(this.mode === 'uncheck' ? 1 : 2);
        this.checkedItems = [];
      },

      changeUnit() {
        this.$server('org.department', {
          company: this.curUnit,
        }, 1).then(data => {
          this.curDepartment = '';
          this.receive = '';
          this.departments = data;
        })
      },

      changeDepartment() {
        this.$server('org.user', {
          company: this.curUnit,
          department: this.curDepartment
        }, 2).then(data => {
          this.receive = '';
          this.receives = data;
        })
      },
      viewBigImg(e) {
        this.$kkui.dialog({
          width: '90%',
          height: '90%',
          cont: `<img src="${e.currentTarget.getAttribute('src')}" style="width:100%; height100%;object-fit:contain;" />`
        })
      },

      initSize() {
        const W = window.screen.width, H = document.body.clientHeight;
        let headerHeight = 61;
        if (W <= 1400) {
          headerHeight = 51;
        }
        this.width = W * 0.75 / 4;
        this.height = this.width * 9 / 16;
        this.listHeight = (this.height - 20) * 4 - 41;
      },

      handle(status, flag) {
        const multFlag = this.checkedItems.length > 1;
        const do1 = () => { // 稽核
          this.$refs.dialog.show = true;
          this.dialogCfg.width = 290;
          this.dialogCfg.height = 240;
          this.dialogCfg.title = '稽核';
          this.dialogCfg.submit = () => {
            if (!this.evtType) {
              this.$kkui.msg({
                icon: 0,
                cont: '请选择稽核事件的类型！'
              });
              return false;
            }
            this.$kkui.alert({
              icon: 0,
              cont: multFlag ? '确定统一稽核这些事件类型吗？' : '确定稽核此事件类型吗？',
              callback: () => {

                this.$server('monitor.multEvtHandle.jihe', this.checkedItems.map(item => {
                  return {
                    eventTypeTwoCode: this.evtType,
                    note: this.note,
                    id: item.id
                  }
                })).then(data => {
                  this.$kkui.msg({
                    icon: 1,
                    cont: '事件稽核成功！'
                  });
                  this.note = '';
                  this.$refs.dialog.show = false;
                  this.checkedItems = [];
                  this.loadEventList(1);
                })
              }
            })
          };
        };

        const do2 = () => { // 忽略
          if (flag) {
            const multFlag = this.checkedItems.length > 1;
            this.fbFormData = {
              handle: [this.kuaisulu],
              expectTimeTwoNum: '5',
              remark2: ''
            };

            this.$refs.dialog2.show = true;
            this.dialogCfg.width = 550;
            this.dialogCfg.height = 380;
            this.dialogCfg.title = '发布';
            this.dialogCfg.submit = () => {
              this.$refs['fun1Form'].validate((valid) => {
                if (valid) {
                  this.$kkui.alert({
                    icon: 0,
                    cont: multFlag ? '确定统一发布这些事件吗？' : '确定发布此事件吗？',
                    callback: () => {
                      this.fbFormData.handle = this.fbFormData.handle.map(item => {
                        return parseInt(item);
                      });
                      this.$server('monitor.multEvtHandle.fabu', this.checkedItems.map(item => {
                        return {
                          id: item.id,
                          state: 3,
                          dispatcher: this.$kkui.cache.get('user')['departmentId'],
                          ...this.fbFormData
                        }
                      }), 1).then(data => {
                        this.$kkui.msg({
                          icon: 1,
                          cont: '事件发布成功！'
                        });

                        this.fbFormData = {
                          handle: [],
                          expectTimeTwoNum: '5',
                          remark2: ''
                        };
                        this.receive = '';
                        this.receives = [];
                        this.curDepartment = '';
                        this.departments = [];
                        this.units = [];
                        this.curUnit = '';
                        this.$refs.dialog2.show = false;
                        this.checkedItems = [];
                        this.loadEventList(2);
                      })
                    }
                  })
                }
              });
            };
          } else {
            const multFlag = this.checkedItems.length > 1;
            this.$kkui.alert({
              icon: 0,
              cont: multFlag ? '确定统一忽略发布这些事件吗？' : '确定忽略发布此事件吗？',
              callback: () => {
                this.$server('monitor.multEvtHandle.hl', this.checkedItems.map(item => {
                  return {
                    pushInterface: false,
                    mobile: this.receive,
                    id: item.id
                  }
                }), 1).then(data => {
                  this.$kkui.msg({
                    icon: 1,
                    cont: '事件忽略成功！'
                  });
                  this.$refs.dialog.show = false;
                  this.checkedItems = [];
                  this.loadEventList(2);
                })
              }
            })
          }
        };
        [do1, do2][status - 1]();


      }
    }
  }
</script>

<style scoped lang="scss">
  @import "~css/check.scss";

  section {
    gap: 0 !important;
  }

  .left {
    width: 75%;
    height: 100%;
  }

  .right {
    width: 25%;
    height: 100%;
    overflow: hidden;
    /*background-color: #e0e0e0;*/
    background-color: #fff;
    padding: 10px 15px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    h4 {
      height: 30px;
      line-height: 30px;
      border-bottom: 1px solid #ccc;
      margin-bottom: 10px;
    }

    .checkedList {
      .content {
        overflow-y: auto;
        overflow-x: hidden;
        font-size: 13px;
      }

      .list-item {
        margin: 5px 0;
        padding: 5px;
        display: flex;
        gap: 10px;
        background-color: #f6f6f6;

        ul {
          flex: 1;
        }

        .img {
          width: 150px;
          cursor: pointer;

          img {
            width: 100%;
            border: 1px solid #aaa;
            padding: 2px;
            box-sizing: border-box;
          }
        }
      }

      .list-item:last-child {
        border-bottom: none;
      }


      li {
        color: #828282;
      }

      label {
        color: #404040;
        margin-right: 5px;
      }
    }

    .action {
      display: flex;
      flex-direction: column;
      justify-content: center;

      border-top: 1px solid #ccc;
      margin-top: 10px;
      box-sizing: border-box;
    }


  }

  /deep/ .tools {

    .tools-group {
      width: 130px;
      float: left;
      height: 100px;
    }
  }

  /deep/ .el-form-item {
    margin-bottom: 20px;
  }

  /deep/ .eventInfoBox .el-form-item__label {
    width: 100%;
    line-height: 24px;
    padding: 0;
  }

</style>
